
-- 导入redis
local redis = require('resty.redis')
local _M = {}
-- 初始化redis
local config = {
    -- host = "23.105.193.189",
    host = "127.0.0.1",
    -- host = "192.168.130.191",
    port = 6379,
    database = "0",
    user = "root",
    password = "123123",
    max_package_size = 1024--,
    --charset = "utf-8"gt
}


--function _M.new( self )
-- 查询redis的方法 ip和port是redis地址，key是查询的key
function _M.new(self)
    --设置超时（毫秒）
    local red = redis:new()
    red:set_timeouts(1000, 1000, 1000)
    local ok, err = red:connect(config.host ,config.port)
    if not ok then
        close_redis(red)
     --   errlog("Cannot connect  "..err);
        local reponseJson =  ' {\"code\":900,\"data\":null,\"detail\":\""..err.."\",\"msg\":\"连接redis失败。\"} '
        ngx.say(reponseJson)
        ngx.exit(ngx.status)
       -- return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    end
 --   ngx.say(ngx.ERR,"Cannot connect  "..red)
    return red
end
-- 关闭redis连接的工具方法，其实是放入连接池
 function _M.close_redis(self,red)
    local pool_max_idle_time = 10000 -- 连接的空闲时间，单位是毫秒
    local pool_size = 100 --连接池大小
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.log(ngx.ERR, "放入redis连接池失败: ", err)
    end
end



-- 查询redis的方法 ip和port是redis地址，key是查询的key
 function _M.read_redis(self,ip, port, key)
    -- 获取一个连接
    local ok, err = red:connect(ip, port)
    if not ok then
        ngx.log(ngx.ERR, "连接redis失败 : ", err)
        return nil
    end
    -- 查询redis
    local resp, err = red:get(key)
    -- 查询失败处理
    if not resp then
        ngx.log(ngx.ERR, "查询Redis失败: ", err, ", key = " , key)
    end
    --得到的数据为空处理
    if resp == ngx.null then
        resp = nil
        ngx.log(ngx.ERR, "查询Redis数据为空, key = ", key)
    end
    close_redis(red)
    return resp
end
-- 查询redis的方法 ip和port是redis地址，key是查询的key
 function _M.read_redis(self,ip, port, key)
    -- 获取一个连接
    local ok, err = red:connect(ip, port)
    if not ok then
        ngx.log(ngx.ERR, "连接redis失败 : ", err)
        return nil
    end
    -- 查询redis
    local resp, err = red:get(key)
    -- 查询失败处理
    if not resp then
        ngx.log(ngx.ERR, "查询Redis失败: ", err, ", key = " , key)
    end
    --得到的数据为空处理
    if resp == ngx.null then
        resp = nil
        ngx.log(ngx.ERR, "查询Redis数据为空, key = ", key)
    end
    close_redis(red)
    return resp
end

-- 封装函数，发送http请求，并解析响应
 function _M.read_http(path, params)
    local resp = ngx.location.capture(path,{
        method = ngx.HTTP_GET,
        args = params,
    })
    if not resp then
        -- 记录错误信息，返回404
        ngx.log(ngx.ERR, "http查询失败, path: ", path , ", args: ", args)
        ngx.exit(404)
    end
    return resp.body
end

return _M
